const {SerialPort} = require("serialport");


const air105 = require("./device/air105");
const stm32f10x = require("./device/stm32f10x");

// 串口实例对象
let PORT_INSTANCE = undefined;

function open(serialConfig) {
    if (PORT_INSTANCE && PORT_INSTANCE.isOpen) {
        console.log('Serial opened already, ', serialConfig.com)
        return
    }

    // 串口不存在，或串口已关闭
    PORT_INSTANCE = new SerialPort({
        path: serialConfig.com, // 串口 COM 号
        // autoOpen: false      // 是否自动打开串口，默认自动打开
        baudRate: serialConfig.baudRate ? serialConfig.baudRate : 115200
    }, err => {
        if (err) {
            console.log('Serial open failed: ', serialConfig.com, err)
            return
        }

        console.log('Serial open success, ', serialConfig.com)
    });
}

async function sendSerialPortData(serialConfig) {
    // 打开串口
    open(serialConfig)

    // 注册错误统一处理
    PORT_INSTANCE.on('error', err => {
        if (err) console.log('port error:', err)
    });

    // 烧录程序
    switch (serialConfig.deviceType) {
        case 'stm32':
            stm32f10x.download(PORT_INSTANCE)
            break
        case 'air10x':
            air105.download(PORT_INSTANCE)
            break
        default:
            break
    }

    // 关闭串口
    // if (PORT_INSTANCE && PORT_INSTANCE.isOpen) {
    //     PORT_INSTANCE.close(err => {
    //         if (err) {
    //             console.log('Serial close error, ', PORT_INSTANCE.path)
    //             return
    //         }
    //         console.log('Serial closed already, ', serialConfig.com)
    //     })
    // }
}


exports.sendSerialPortData = sendSerialPortData;
